package com.anuo.app.modules.system.controller;

import com.anuo.app.common.globalhandle.AppException;
import com.anuo.app.common.globalhandle.BaseController;
import com.anuo.app.common.thirdparty.PictureUtil;
import com.anuo.app.common.utils.DateUtil;
import com.anuo.app.common.utils.FileUtil;
import com.anuo.app.common.utils.IdUtil;
import com.anuo.app.common.utils.Utils;
import com.anuo.app.modules.system.entity.Fileinfo;
import com.anuo.app.modules.system.service.FileService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * 文件上传下载
 * 实现状态: 上传下载已实现
 */

@RestController
public class FileController extends BaseController {
    @Autowired
    ServletContext context;
    @Autowired
    FileService fileService;

    /**
     * 上传图片到云服务
     * @param inputFile
     * @param request
     * @return
     */
    @PostMapping(value = "v1/apiPictureUploadToCloud")
    public String apiPictureUploadToCloud(@RequestParam("file") MultipartFile inputFile
            , HttpServletRequest request) {
        //验证token
        String token = request.getHeader("token");
        checkToken(token);
        //上传文件
        if (!inputFile.isEmpty()) {
            try {
                String extension = inputFile.getOriginalFilename().split("\\.")[1];
                String fileName = IdUtil.getUUID() + "." + extension;
                PictureUtil.uploadPicture(fileName, inputFile.getInputStream());
                return rspSuccess(fileName);
            } catch (Exception e) {
                throw new AppException("", e);
            }
        } else {
            return rspError("检测到没有任何文件,请选择一个文件");
        }
    }

    /**
     * 从云服务获取图片url
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "v1/apiGetPictureUrlFromCloud", produces = {"application/json;charset=UTF-8"})
    public String apiGetPictureUrlFromCloud(HttpServletRequest request, HttpServletResponse response) {
        //验证token
        String token = request.getHeader("token");
        checkToken(token);
        //获取url
        String fileName = request.getHeader("fileName");
        String width = request.getHeader("width");
        String high = request.getHeader("high");
        String url = PictureUtil.getPictureUrl(
                fileName
                , Integer.parseInt(width)
                , Integer.parseInt(high));
        return rspSuccess(url);
    }

    /**
     * 删除云服务中的图片
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "v1/apiDeletePictureInCloud", produces = {"application/json;charset=UTF-8"})
    public String apiDeletePictureInCloud(HttpServletRequest request, HttpServletResponse response) {
        //验证token
        String token = request.getHeader("token");
        checkToken(token);
        //删除文件
        String fileName = request.getHeader("fileName");
        PictureUtil.deletePicture(fileName);
        return rspSuccess();
    }

    /**
     * 上传文件到本地服务器
     * @param inputFile
     * @param request
     * @return
     */
    @PostMapping(value = "v1/apiFileUpload")
    public String apiFileUpload(@RequestParam("file") MultipartFile inputFile, HttpServletRequest request) {
        //验证token
        //String token=request.getHeader("token");
        //checkToken(token);
        //上传文件
        Fileinfo fileInfo = new Fileinfo();
        if (!inputFile.isEmpty()) {
            try {
                String extension = inputFile.getOriginalFilename().split("\\.")[1];
                //获取默认上传目录
                String uploadDirectory = "/uploaded/" + DateUtil.getCurrentDate(); //FileUtils.getDefaultUploadPath();

                FileUtil.makesureDirExists(uploadDirectory);
                //上传到指定目录
                File destinationFile = new File(uploadDirectory +
                        File.separator + IdUtil.getUUID() + "." + extension);
                inputFile.transferTo(destinationFile);
                //保存此文件信息到数据库
                fileInfo.preInsert();
                fileInfo.setMaster_id("ddd");
                fileInfo.setMaster_type("user");
                String filePath = destinationFile.getPath();
                fileInfo.setFilepath(filePath);
                fileInfo.setSize(inputFile.getSize());
                fileService.insertFileinfo(fileInfo);
                return rspSuccess(filePath);
            } catch (Exception e) {
                return rspError(e.toString());
            }
        } else {
            return rspError("检测到没有任何文件, 请检测你的请求");

        }

    }

    /**
     * 从本地服务器下载文件
     * @param body
     * @param request
     * @param response
     */
    @PostMapping(value = "v1/apiFileDownload")
    public void apiFileDownload(@RequestBody String body, HttpServletRequest request, HttpServletResponse response) {
        //验证token
//        String token = request.getHeader("token");
//        checkToken(token);
        //下载文件
        try {

            File file = new File("D:\\images\\tooopen_sy_201956178977.jpg");
            FileInputStream inputStream = new FileInputStream(file);

            //InputStream inputStream = new FileInputStream(body);
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}